package be.kuleuven.mume.paginas;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import be.kuleuven.mume.R;
import be.kuleuven.mume.arrayAdapters.UpdatesArrayAdapter;
import be.kuleuven.mume.framework.Mobilenvi;
import be.kuleuven.mume.framework.Update;
import be.kuleuven.mume.hulpklassen.AuthenticatedChecker;
import be.kuleuven.mume.hulpklassen.DataFetcher;
import be.kuleuven.mume.hulpklassen.AuthenticatedChecker.AuthenticatedListener;
import be.kuleuven.mume.hulpklassen.JSONParser.UpdatesParser;
import be.kuleuven.mume.listProxys.DeviderProxy;
import be.kuleuven.mume.listProxys.LastCellLoadingProxy;

public class StartPagina extends Activity implements AuthenticatedListener{
	private List<Update> updates;
	private UpdatesArrayAdapter adapter;
	private LastCellLoadingProxy adapterProxy;
	private UpdatesParser parser;
	private DataFetcher<Update> dataFetcher;
	private AuthenticatedChecker checker;
	private static final int LOGIN_ID = 0;
	private static final int URL_ID = 1;
	private static final int REFRESH_ID = 2;
	private boolean isAuthenticated = false;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.startpagina);
        
        checker = new AuthenticatedChecker(this, this);
        checker.checkAuthenticated(true);
    }
    
	public void AuthenticationReceived() {
		loadView();
		this.isAuthenticated = true;
	}
	@Override
	protected void onResume() {
		super.onResume();
		checker.checkAuthenticated(false);
	}
	
    private void loadView(){
       setBtnListeners();
        
        ListView table = (ListView)findViewById(R.id.updates_start);
		Object o = getLastNonConfigurationInstance();
		if(o != null)
			((Data)o).load();
		else {
			updates = new ArrayList<Update>();
			this.adapter = new UpdatesArrayAdapter(this, updates);
			DeviderProxy deviderAdapter = new DeviderProxy(this, adapter);
			
	        adapterProxy = new LastCellLoadingProxy(deviderAdapter);
	        adapterProxy.noDataString_ID = R.string.geen_updates;
	        
	        table.setAdapter(adapterProxy);
	        parser = new UpdatesParser();
	        dataFetcher = new DataFetcher<Update>(parser, Update.URL, table, updates, this.getBaseContext()) {
				public void DataReceived() {
					if(!dataFetcher.hasMoreData())
						adapterProxy.setIsLoading(false);
					adapter.notifyDataSetChanged();
				}
			};
		}
    }
    
	private void setBtnListeners() {
		ImageButton agenda = (ImageButton) findViewById(R.id.agenda);
        
        agenda.setOnClickListener(new View.OnClickListener() {

	        public void onClick(View view) {
	        	Intent i = new Intent(StartPagina.this, AgendaTabBar.class);
	        	startActivity(i);
	        }
	    });
        
        ImageButton vakken = (ImageButton) findViewById(R.id.vakken);
        
        vakken.setOnClickListener(new View.OnClickListener() {

	        public void onClick(View view) {
	        	Intent i = new Intent(StartPagina.this, VakkenTabel.class);
	        	startActivity(i);
	        }
	    });
        
        ImageButton updates = (ImageButton) findViewById(R.id.updates_btn);
        
        updates.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent i = new Intent(StartPagina.this, UpdatesTabBar.class);
				startActivity(i);
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if(!isAuthenticated)
			menu.add(0, LOGIN_ID,0, R.string.login);
		menu.add(0, URL_ID, 1, R.string.changeUrl);
		menu.add(0,REFRESH_ID,2, R.string.refresh);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()){
		case LOGIN_ID:
			checker.checkAuthenticated(true);
			break;
		case URL_ID:
			showUrlChangeDialog();
			break;
		case REFRESH_ID:
			updates.clear();
			checker.checkAuthenticated(true);
		}

		return super.onMenuItemSelected(featureId, item);
	}

	private void showUrlChangeDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle(R.string.changeUrl);
		alert.setMessage("");

		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		alert.setView(input);
		input.setText(Mobilenvi.getSingelton().BASEURL);

		alert.setPositiveButton(R.string.bevestig, new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  String value = input.getText().toString();
		  Mobilenvi.getSingelton().setBaseUrl(value);
		  }
		});

		alert.setNegativeButton("Cancel", null);

		alert.show();
	}
	
	private static class Data{
		private UpdatesParser parser;
		private List<Update> updates;
		private UpdatesArrayAdapter adapter;
		private StartPagina pagina;
		private DataFetcher<Update> datafetcher;
		
		public Data(StartPagina pagina){
			this.pagina = pagina;
		}
		
		public void store(){
			this.adapter = pagina.adapter;
			this.parser = pagina.parser;
			this.updates = pagina.updates;
			this.datafetcher = pagina.dataFetcher;
		}
		
		public void load(){
			pagina.adapter = this.adapter;
			pagina.parser = this.parser;
			pagina.updates = this.updates;
			pagina.dataFetcher = this.datafetcher;
		}
	}
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		Data d = new Data(this);
		d.store();
		return d;
	}
}